<template>
  <div class="assessment-list-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">
        <i :class="pageConfig.icon"></i>
        {{ pageConfig.title }}
      </h2>
      <p class="page-subtitle">{{ pageConfig.subtitle }}</p>
    </div>

   

    <!-- 统计卡片 -->
    <div class="stats-container">
      <div class="stat-card total">
        <div class="stat-icon">
          <i :class="pageConfig.stats.totalIcon"></i>
        </div>
        <div class="stat-content">
          <h3>{{ statistics.total }}</h3>
          <p>{{ pageConfig.stats.totalLabel }}</p>
        </div>
      </div>
      
      <template v-if="listType === 'todo'">
        <div class="stat-card success">
          <div class="stat-icon">
            <i :class="pageConfig.stats.successIcon"></i>
          </div>
          <div class="stat-content">
            <h3>{{ statistics.success }}</h3>
            <p>{{ pageConfig.stats.successLabel }}</p>
          </div>
        </div>
        
        <div class="stat-card warning">
          <div class="stat-icon">
            <i :class="pageConfig.stats.warningIcon"></i>
          </div>
          <div class="stat-content">
            <h3>{{ statistics.warning }}</h3>
            <p>{{ pageConfig.stats.warningLabel }}</p>
          </div>
        </div>
      </template>
    </div>

    <!-- 数据列表 -->
    <div class="table-container">
      <div class="section-header">
        <i class="el-icon-s-grid"></i>
        <span>{{ pageConfig.tableTitle }}</span>
        <div class="header-actions">
          <el-button type="text" @click="refreshData">
            <i class="el-icon-refresh"></i>
            刷新
          </el-button>
        </div>
      </div>
      
      <el-table
        v-loading="loading"
        :data="filteredData"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        
        <el-table-column prop="taskName" label="任务名称" min-width="200" show-overflow-tooltip></el-table-column>
        
        <!-- 待测评任务列 -->
        <template v-if="listType === 'todo'">
          <el-table-column prop="startTime" label="开始时间" width="150" align="center"></el-table-column>
          
          <el-table-column prop="endTime" label="截止时间" width="150" align="center">
            <template slot-scope="scope">
              <span :class="{ 'expired-time': isTaskExpired(scope.row.endTime) }">
                {{ scope.row.endTime }}
              </span>
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template slot-scope="scope">
              <el-tag :type="getTodoStatusTagType(scope.row)" size="small">
                {{ getTodoStatusText(scope.row) }}
              </el-tag>
            </template>
          </el-table-column>
        </template>
        
        <!-- 测评记录列 -->
        <template v-if="listType === 'record'">
          <el-table-column prop="startTime" label="开始时间" width="150" align="center"></el-table-column>
          
          <el-table-column prop="endTime" label="完成时间" width="150" align="center"></el-table-column>
          
          <el-table-column label="等级判断方式" width="120" align="center">
            <template slot-scope="scope">
              <el-tag :type="getLevelJudgeTagType(scope.row.levelJudge)" size="small">
                {{ getLevelJudgeText(scope.row.levelJudge) }}
              </el-tag>
            </template>
          </el-table-column>
        </template>
        
        <!-- 操作列 -->
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template slot-scope="scope">
            <template v-if="listType === 'todo'">
              <el-button
                size="mini"
                type="primary"
                @click="handleStartTask(scope.row)"
                :disabled="isTaskExpired(scope.row.endTime)"
              >
                {{ isTaskExpired(scope.row.endTime) ? '已过期' : '开始测评' }}
              </el-button>
            </template>
            
            <template v-if="listType === 'record'">
              <el-button size="mini" type="primary" @click="viewResult(scope.row)">
                查看详情
              </el-button>
              <!-- <el-button size="mini" type="danger" @click="deleteRecord(scope.row)">
                删除
              </el-button> -->
            </template>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { getTodoPendingList, getCompleteList } from '@/api/system/assess'

export default {
  name: 'AssessmentList',
  data() {
    return {
      loading: false,
      listType: 'todo', // 'todo' 或 'record'
      
      // 查询参数
      queryParams: {
        taskName: '',
        status: '',
        assessmentType: '',
        pageNum: 1,
        pageSize: 20
      },
      
      // 日期范围
      dateRange: [],
      
      // 统计数据
      statistics: {
        total: 0,
        success: 0,
        warning: 0
      },
      
      // 数据列表
      dataList: [],
      total: 0
    }
  },
  
  computed: {
    // 页面配置
    pageConfig() {
      if (this.listType === 'todo') {
        return {
          title: '待测评任务',
          subtitle: '查看所有待完成的心理测评任务',
          icon: 'el-icon-document',
          tableTitle: '任务列表',
          stats: {
            totalIcon: 'el-icon-data-line',
            totalLabel: '总任务数',
            successIcon: 'el-icon-time',
            successLabel: '进行中',
            warningIcon: 'el-icon-warning',
            warningLabel: '已过期'
          }
        }
      } else {
        return {
          title: '测评记录',
          subtitle: '查看所有已完成的心理测评记录',
          icon: 'el-icon-document-checked',
          tableTitle: '测评记录',
          stats: {
            totalIcon: 'el-icon-data-analysis',
            totalLabel: '总测评数'
          }
        }
      }
    },
    
    // 过滤后的数据
    filteredData() {
      let filtered = [...this.dataList]
      
      // 任务名称筛选
      if (this.queryParams.taskName) {
        filtered = filtered.filter(item => 
          item.taskName.includes(this.queryParams.taskName)
        )
      }
      
      if (this.listType === 'todo' && this.queryParams.status) {
        if (this.queryParams.status === 'expired') {
          filtered = filtered.filter(item => this.isTaskExpired(item.endTime))
        } else if (this.queryParams.status === 'ongoing') {
          filtered = filtered.filter(item => !this.isTaskExpired(item.endTime))
        }
      }
      
      if (this.listType === 'record' && this.queryParams.assessmentType) {
        filtered = filtered.filter(item => 
          item.assessmentType === this.queryParams.assessmentType
        )
      }
      
      return filtered
    }
  },
  
  async mounted() {
    // 获取路由参数
    this.listType = this.$route.query.type || 'todo'
    
    console.log(`${this.pageConfig.title}页面初始化中...`)
    await this.loadData()
    console.log(`${this.pageConfig.title}页面初始化完成！`)
  },
  
  watch: {
    // 监听路由变化
    '$route'(to, from) {
      if (to.query.type !== this.listType) {
        this.listType = to.query.type || 'todo'
        this.resetQuery()
        this.loadData()
      }
    }
  },
  
  methods: {
    // 加载数据
    async loadData() {
      this.loading = true
      try {
        if (this.listType === 'todo') {
          await this.loadTodoTasks()
        } else {
          await this.loadRecords()
        }
        this.calculateStatistics()
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败，请重试')
      } finally {
        this.loading = false
      }
    },
    
    // 加载待测评任务
    async loadTodoTasks() {
      try {
        const response = await getTodoPendingList({
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize
        })
        
        if (response.code === 200) {
          this.dataList = response.rows || []
          this.total = response.total
          console.log('加载了', this.dataList.length, '个待测评任务')
        } else {
          this.$message.error(response.msg || '获取任务列表失败')
        }
      } catch (error) {
        console.error('获取任务列表失败:', error)
        this.$message.error('获取任务列表失败')
      }
    },
    
    // 加载测评记录
    async loadRecords() {
      try {
        const response = await getCompleteList({
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize
        })
        
        if (response.code === 200) {
          this.dataList = response.rows.map(record => ({
            ...record,
            assessmentType: this.getRandomAssessmentType(),
            levelJudge: Math.floor(Math.random() * 4) + 1
          }))
          this.total = response.total
          console.log('加载了', this.dataList.length, '条测评记录')
        } else {
          this.$message.error(response.msg || '获取记录列表失败')
        }
      } catch (error) {
        console.error('获取记录列表失败:', error)
        this.$message.error('获取记录列表失败')
      }
    },
    
    // 随机生成测评类型
    getRandomAssessmentType() {
      const types = ['mental_health', 'learning_ability', 'personality', 'emotion_management']
      return types[Math.floor(Math.random() * types.length)]
    },
    
    // 计算统计数据
    calculateStatistics() {
      const total = this.dataList.length
      
      if (this.listType === 'todo') {
        const expired = this.dataList.filter(item => this.isTaskExpired(item.endTime)).length
        const ongoing = total - expired
        
        this.statistics = { total, success: ongoing, warning: expired }
      } else {
        this.statistics = { total }
      }
      
      console.log('统计数据:', this.statistics)
    },
    
    // 检查任务是否过期
    isTaskExpired(endTime) {
      if (!endTime) return false
      const now = new Date()
      const endDate = new Date(endTime)
      return now > endDate
    },
    
    // 待测评任务状态相关方法
    getTodoStatusTagType(task) {
      return this.isTaskExpired(task.endTime) ? 'danger' : 'success'
    },
    
    getTodoStatusText(task) {
      return this.isTaskExpired(task.endTime) ? '已过期' : '进行中'
    },
    
    // 获取等级判断方式标签类型
    getLevelJudgeTagType(levelJudge) {
      const typeMap = {
        1: 'warning',  // 测评预警（橙色）
        2: 'primary',  // 二阶段访谈（蓝色）
        3: 'info',     // 咨询评估（灰色）
        4: 'success'   // 综合评定（绿色）
      }
      return typeMap[levelJudge] || 'info'
    },
    
    // 获取等级判断方式文本
    getLevelJudgeText(levelJudge) {
      const textMap = {
        1: '测评预警',
        2: '二阶段访谈',
        3: '咨询评估',
        4: '综合评定'
      }
      return textMap[levelJudge] || '未知'
    },
    
    // 查询
    handleQuery() {
      console.log('执行查询:', this.queryParams, this.dateRange)
      this.calculateStatistics()
    },
    
    // 重置查询
    resetQuery() {
      this.queryParams = {
        taskName: '',
        status: '',
        assessmentType: '',
        pageNum: 1,
        pageSize: 20
      }
      this.dateRange = []
      this.handleQuery()
    },
    
    // 刷新数据
    async refreshData() {
      this.$message.info('正在刷新数据...')
      await this.loadData()
      this.$message.success('数据刷新成功')
    },
    
    // 分页相关
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.loadData()
    },
    
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.loadData()
    },
    
    // 待测评任务操作
    handleStartTask(task) {
      if (this.isTaskExpired(task.endTime)) {
        this.$message.warning('任务已过期，无法开始测评')
        return
      }
      
      if (!task || !task.id) {
        this.$message.error('任务信息不完整，无法打开')
        return
      }
      
      if (!task.scaleIds) {
        this.$message.error('该任务没有关联量表，无法填写')
        return
      }
      
      // 跳转到测评引导页面
      this.$router.push({
        path: '/assessment/guide',
        query: {
          id: task.id,
          scaleId: task.scaleIds,
          taskName: task.taskName
        }
      })
    },
    
    // 测评记录操作
    viewResult(record) {
      if (!record || !record.id) {
        this.$message.error('记录信息不完整，无法查看')
        return
      }
      
      if (!record.scaleIds) {
        this.$message.error('该记录没有关联量表，无法查看')
        return
      }
      
      window.open(`/questionnaire?scaleId=${record.scaleIds}&taskId=${record.id}&viewType=result`)
    },
    
    deleteRecord(record) {
      this.$confirm(`确定要删除测评记录"${record.taskName}"吗？`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.dataList.findIndex(item => item.id === record.id)
        if (index > -1) {
          this.dataList.splice(index, 1)
          this.total = this.dataList.length
          this.calculateStatistics()
          this.$message.success('删除成功')
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.assessment-list-container {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: calc(100vh - 84px);
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-title i {
  margin-right: 12px;
  color: #409EFF;
}

.page-subtitle {
  font-size: 16px;
  color: #606266;
  margin: 0;
}

.filter-container {
  background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
  padding: 24px;
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e2e8f0;
}

.section-header i {
  font-size: 18px;
  color: #409EFF;
  margin-right: 8px;
}

.section-header span {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.header-actions {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.stats-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-card.total .stat-icon {
  background: linear-gradient(45deg, #909399, #b1b3b8);
}

.stat-card.success .stat-icon {
  background: linear-gradient(45deg, #67c23a, #85ce61);
}

.stat-card.warning .stat-icon {
  background: linear-gradient(45deg, #f56c6c, #f78989);
}

.stat-card.info .stat-icon {
  background: linear-gradient(45deg, #409EFF, #36a3f7);
}

.stat-content h3 {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 4px 0;
}

.stat-content p {
  font-size: 14px;
  color: #606266;
  margin: 0;
}

.table-container {
  background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background: linear-gradient(145deg, #f0f2f5 0%, #e6e8eb 100%);
  color: #2c3e50;
  font-weight: 600;
  text-align: center;
}

.expired-time {
  color: #f56c6c;
  font-weight: 600;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .assessment-list-container {
    padding: 16px;
  }
  
  .stats-container {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>